import { HttpError, toSuccess, useEntityManager } from "@sker/core";
import { AutoUser, KsDevice } from "@sker/entities";
import { useData } from "@sker/runtime";
import { z } from "zod";


export default async () => {
    const input = z.object({
        token: z.string(),
        deviceid: z.any()
    });
    const body = input.parse(useData())

    return await useEntityManager(async m => {
        const user = await m.findOne(AutoUser, { where: { token: body.token } })
        if (!user) throw new HttpError(`请重新登录`)
        const device = await m.findOne(KsDevice, { where: { id: parseInt(body.deviceid) } })
        if (!device) {
            throw new HttpError(`请输入正确的设备编号`)
        }
        if (device.owner !== user.mobile) {
            throw new HttpError(`此设备不是您的设备，请检查`)
        }
        await m.update(KsDevice, device.id, { owner: '' })
        await m.update(AutoUser, user.id, { device_count: user.device_count - 1 })
        return toSuccess(true)
    })
}
